<template>
    <div style="display: flex;flex-direction: column;background-color: bisque;">
        <span>ai-flux</span>
        <button @click="handleStreamTest">test</button>
        <button @click="handleStreamTest2">test2</button>
        ---

        <div>
            输入问题
            <input type="text" v-model="question"></input>
            <button @click="handleStreamAiFlux">aiFlux</button>
        </div>
        <div> 
            <v-md-preview :text="answer"></v-md-preview>
        </div>


    </div>
</template>
<script setup lang="ts">

import { URL_STREAM_TEST, URL_STREAM_TEST2, URL_STREAM_AI_FLUX } from '@/api/ai';
import { sseRequestGet } from '@/util/sse-request';
import { ref } from 'vue';

// 问题与答案
const question = ref('')
const answer = ref('')

/**
 * 页面初始化
 */
function init() {
    console.log('ai flux')
    console.log(import.meta.env.VITE_APP_BASE_API)
    const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
    try {
        const jsonObject = JSON.parse(jsonString);
        console.log(jsonObject.name); // 输出: John
    } catch (error) {
        console.error("解析 JSON 字符串时发生错误:", error);
    }
}
init();

/**
 * 流数据测试
 */
function handleStreamTest() {
    const eventSource = new EventSource(URL_STREAM_TEST);

    eventSource.onmessage = function (event) {
        // 处理接收到的数据
        console.log('接收到数据:', event.data);
        // 通常数据是文本，你可以将其追加到页面上
        //   document.getElementById('output').innerHTML += event.data;
    };

    eventSource.onerror = function (error) {
        console.error('EventSource 错误:', error);
        // 发生错误时，可以关闭连接
        eventSource.close();
    };
}


function handleStreamTest2() {
    sseRequestGet(URL_STREAM_TEST2, item => {
        console.log(item)
    })
}

function handleStreamAiFlux() {
    answer.value = ''
    sseRequestGet(URL_STREAM_AI_FLUX + '?prompt=' + question.value, item => {
        console.log(item)
        const itemJson=JSON.parse(item.data)
        answer.value+=itemJson.message
    })
}



</script>